<template>
  <div class="warpper-box">
    <div class="inner_box">
     <form-create 
     v-model="params.fApi" 
     :rule="params.rule" 
     :option="params.option" 
     @btn-search-click="loadList(true)" 
     @btn-add-click="add(true)" 
     @btn-mover-batch-click="moverBlacklist"
     @btn-del-batch-click="delBatch"
     @btn-upload-click="uploadXlsx"
     @btn-reset-click="reset"/>
    <system-list
     :key="keys"
     :tableData="tables.tableData" 
     :tableLabel="tables.tableLabel" 
     :models="tables" 
     @on-search-click="loadList"
     @on-selection-click="selectionChange"
     @on-del-click="del"
     @on-resetPwd-click="resetPwd"
     @on-enable-click="onEnable"
     />
    </div>

    <el-dialog :title="tipsForm.title" :visible.sync="tipsForm.visible" width="600px" :close-on-click-modal="false">
       <el-form size="small" :model="tipsForm" label-width="100px" ref="tipsForm">
        <el-form-item label="移入供应商">
          <el-tag v-for="item in selectItem" :key="item.id">{{ item.name }}</el-tag>
        </el-form-item>
        <el-form-item label="移入理由" prop="reason" :rules="[{required: true, message:'请输入移入理由', trigger: 'blur'}]">
          <el-input
            type="textarea"
            :rows="3"
            v-model="tipsForm.reason"
            placeholder="请输入移入理由"
          ></el-input>
        </el-form-item>
       </el-form>
        <div slot="footer" class="dialog-footer">
              <el-button size="small" @click="tipsForm.visible = false">取 消</el-button>
              <el-button size="small" type="primary" @click="submitAddly('tipsForm')">提交</el-button>
          </div>
    </el-dialog>

   

  </div>
</template>

<script>
import store from '@/store'
import moment from "moment";
import { PARAMS_SUPPLIER_USER,OPTION_INLINE,USER_SUPPLIER_LABEL,OPTION_BLOCK} from "./systemUser/system_form"
import SystemList from "./systemUser/system_list"
import { arrayFormat,loginMD5 } from "@/utils/index"
import { getUserList, addUserSave, delUser, delBatchUser, disableUser, enableUser, roleUser, resetPwdUser } from "@/api/system_api"
import { supplierMoveBlacklist,supplierPageFind } from "@/api/supplier_api";
import { xlsx } from "@/utils/xlsx"
export default {
  components:{
    SystemList
  },
  data() {
    return {
      keys:0,
      params:{
        fApi:{},
        rule:PARAMS_SUPPLIER_USER,
        option:OPTION_INLINE
      },
      tables:{
        total:0,
        width:'260',
        hackReset:true,
        fixed:false,
        tableData:[],
        tableLabel: USER_SUPPLIER_LABEL
      },
      page:{
        pageNum:1,
        pageSize:10,
      },
      supplierOptions:[],
      selectItem: [],
      tipsForm: {
        visible: false,
       reason:'',
        callbackType:'',
        title:''
      }
    };
  },
  mounted() {
    this.params.fApi.setValue({ "name": "", "statusFlag": "", "phone": "" });
    this.getSupplierList();
  },
  methods: {
    async getSupplierList() {
      let param = {}
        param.pageNum = 1
        param.pageSize = 100;
      param.tag = "3"
      try {
        const { code, data } = await supplierPageFind(param);
        if (code == 200) {
          this.supplierOptions = data.list
        }
      } finally {
          this.loadList(true);
        }
    },
    async loadList(formData) {
      let params = {};
      let query = this.params.fApi.bind();
      params.name = query.name;
      params.phone = query.phone;
      params.statusFlag = query.statusFlag;
      
      if(formData !== undefined && formData.type === 'page'){
        this.page.pageNum = formData.page;
        this.page.pageSize = formData.pageSize;
      }
      if(formData===true){
        this.page.pageNum = 1;
        this.keys++;
      }
      params.pageNum = this.page.pageNum;
      params.pageSize = this.page.pageSize;
      params.userType = '2'
      const req = await getUserList(params);
      let result = req?.data?.list ?? []
      result.forEach(v=>{
        v.del = true;
        v.resetPwd = true;
        v.statusFlag = '1'
        v.cusmotText = ''
        let indx = this.supplierOptions.map(item => item.id)
        if(indx.includes(v.supplierId)){
          v.statusFlag = '2'
          v.cusmotText = '该供应商已进入黑名单，无法操作账号状态！'
        }
      })
      this.tables.tableData = result;
      
      this.tables.total = req.data.total;
    },
    del(row){
      this.$confirm("确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await delUser(row.id);
        this.$message.success("删除成功");
        this.loadList();
      }).catch(() => {});
    },
    selectionChange(arr){
      this.selectItem = arr;
    },
    delBatch(){
      if(this.selectItem.length === 0){
            return this.$message.error("请勾选要导出的数据！");
        }
        this.$confirm("确认删除", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          let ids = [];
          this.selectItem.forEach(v=>{
            ids.push(v.id)
          })
          const req = await delBatchUser(ids);
          if(req.code === 200){
            this.$message.success("操作成功");
            this.loadList(true);
          }
        }).catch(() => {});
    },
    moverBlacklist() {
       if(this.selectItem.length === 0){
            return this.$message.error("请勾选要移入的数据！");
        }
      this.tipsForm.title = '移入黑名单菜单'
      this.tipsForm.reason = ''
      this.tipsForm.visible = true
    },
    async callApi() {
      let p = 0;
      for (let i = 0; i < this.selectItem.length; i++){
        let item = this.selectItem[i]
        let param = {}
        param.id = item.supplierId
        param.blacklistReason = this.tipsForm.reason
        const { code } =  await supplierMoveBlacklist(param);
        if (code == 200) {
          p++
        }
      }
      if (p == this.selectItem.length) {
        this.$message.success('移入成功');
        this.tipsForm.visible = false
        this.loadList(true);
      }
    },
    submitAddly(formName) {
       this.$refs[formName].validate(async (valid) => {
         if (valid) {
           this.callApi()
        }
      });
    },
    async onEnable(row) {
      if (row.cusmotText) {
        return this.$message.error(row.cusmotText);
      }
      
      let text = row.statusFlag==='1' ?'禁用':'启用';
      let tips = row.statusFlag==='1' ?'禁用成功':'启用成功';
      this.$confirm("确认"+text+"", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        row.statusFlag === '1' ? await disableUser(row.id) : await enableUser(row.id);
        this.$message.success(tips);
        this.loadList();
      }).catch(() => {});
    },
    resetPwd(row){
      this.$confirm("确认重置账号 "+row.account+" 密码为 123456 ", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        const pwd = "123456";
        let params = {
          id:row.id,
          pwd:loginMD5(pwd)
        }
        await resetPwdUser(params);
        this.$message.success('操作成功');
        this.loadList();
      }).catch(() => {});
    },
    reset(){
      this.params.fApi.resetFields();
      this.loadList(true);
    },
    uploadXlsx() {
      if(this.tables.total == 0){
            return this.$message.error("没有可导出的供应商！");
        }
        const that = this;
        this.$prompt('请输入导出数量', '提示', {
          confirmButtonText: '导出',
          cancelButtonText: '取消',
          closeOnClickModal:false,
          inputPlaceholder:'导出数量不能大于列表总条数',
          inputValue:that.tables.total,
          inputValidator:function(val){
            if(!val){
              return false;
            }
            if(val > that.tables.total){
              return false;
            }else{
              return true;
            }
          },
          inputErrorMessage: '导出数量有误'
        }).then(async({ value }) => {
          let params = {};
          params.pageNum = 1;
          params.pageSize = value;
          params.userType = '2'
          const {code,data} = await getUserList(params);
          if (code === 200) {
            console.log(data.list)
            if(data.list && data.list.length > 1){
              let fields = {
                title0: "编号",
                title1: "登录账户",
                title6: "公司名称",
                title2: "真实姓名",
                title3: "手机号",
                title4: "邮箱",
                title5: "创建时间",
              };
              let arry = [];
              let i = 0;
              data.list.forEach(ele => {
                const createTime = moment(ele.createTime).format("YYYY-MM-DD");
                  i++;
                  arry.push({
                      title0: i,
                    title1: ele.account,
                      title6:ele.supplierName,
                      title2: ele.name,
                      title3: ele.phone,
                      title4: ele.email,
                      title5: createTime
                  });
              });
              const manualWidthColumns = [
                { width: 10 },
                { width: 10 },
                { width: 45 },
                { width: 15 },
                { width: 20 },
                { width: 25 },
                { width: 20 }
              ];
              xlsx(arry, fields,manualWidthColumns, "供应商列表");
            }
          }
        }).catch(() => {});
      }
  }
};
</script>
<style>
  .el-cascader--small{
    width: 100% !important;
  }
</style>